<template>
  <div class="cps-search-form">
    <a-row :gutter="24">
      <a-col
        :span="colSpan"
        v-for="(item, index) in showSearchDataList"
        :key="index"
      >
        <div class="flex mb-6px items-center">
          <slot :name="`${item.requestStr}TR`" :record="item">
            <label class="w-120px tar mr-6px"> {{ item.columnName }}: </label>
          </slot>
          <slot :name="`${item.requestStr}CR`" :record="item">
            <a-select
              class="w-full"
              v-if="item.model === 0 || item.model === 6"
              :placeholder="'搜索' + item.columnName"
              :maxTagCount="2"
              :mode="item.model === 6 ? undefined : 'multiple'"
              v-model:value="formdata[item.searchStr]"
              :filter-option="filterOption"
              option-label-prop="label"
              show-search
              allow-clear
              @focus="
                () => {
                  getConfigColumn(item)
                }
              "
            >
              <a-select-option
                v-for="val in item.options"
                :value="val.value"
                :label="val.label"
                :key="val.value"
                >{{ val.label }}</a-select-option
              >
            </a-select>
            <remote-select
              v-if="item.model === 2 && props.menuName"
              :placeholder="'搜索' + item.columnName"
              class="w-full"
              :maxTagCount="1"
              v-model:value="formdata[item.searchStr]"
              :menuName="item.menuName"
              mode="multiple"
              :token-separators="[' ', ',']"
              :columnName="item.searchStr"
            />
            <cps-select
              v-if="item.model === 2 && item.url"
              :placeholder="'搜索' + item.columnName"
              class="w-full"
              :maxTagCount="1"
              :not-found-content="null"
              v-model:value="formdata[item.searchStr]"
              mode="tags"
              :token-separators="[' ', ',']"
              v-bind="item"
            ></cps-select>
            <!-- 建议给个url -->
            <cps-cascader
              v-if="item.model === 4"
              v-model:value="formdata[item.searchStr]"
              class="w-full"
              change-on-select
              :placeholder="'搜索' + item.columnName"
              v-bind="item"
            ></cps-cascader>
            <a-range-picker
              dropdownClassName="date-range"
              v-if="item.model === 1"
              class="w-full"
              allow-clear
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD"
              v-model:value="formdata[item.searchStr]"
              :placeholder="['开始日期', '结束日期']"
            />
            <a-radio-group
              size="small"
              class="w-full"
              v-if="item.model === 5"
              v-model:value="formdata[item.searchStr]"
            >
              <a-radio
                v-for="(val, inde) in item.options"
                :key="inde"
                :value="val.value"
                >{{ val.label }}</a-radio
              >
            </a-radio-group>
            <a-textarea
              class="w-full"
              allow-clear
              v-if="item.model === 3"
              v-model:value="formdata[item.searchStr]"
              :placeholder="'搜索' + item.columnName"
              :row="3"
            ></a-textarea>
            <a-input
              class="w-full"
              allow-clear
              v-if="item.model === 8"
              v-model:value="formdata[item.searchStr]"
              :placeholder="'搜索' + item.columnName"
            ></a-input>
            <a-input-number
              v-if="item.model === 9"
              class="w-full"
              allow-clear
              v-model:value="formdata[item.searchStr]"
              :placeholder="'搜索' + item.columnName"
            >
            </a-input-number>
          </slot>
        </div>
      </a-col>
      <a-col :span="actionSpan" v-if="showSearchDataList.length">
        <a-space style="float: right">
          <cps-button
            :throttle="0"
            size="small"
            type="link"
            @click="toggleMoreFilter"
            v-if="searchDataList.length > DISPLAY_MAX_ON_FOLDED"
          >
            <template v-if="state.isFolder">
              <DownOutlined />更多筛选
            </template>
            <template v-else> <UpOutlined />收起筛选 </template>
          </cps-button>
          <cps-button size="small" @click="onReset">重置</cps-button>
          <cps-button size="small" type="primary" @click="onSearch"
            >搜索</cps-button
          >
        </a-space>
      </a-col>
    </a-row>
  </div>
</template>
<script setup>
import { config } from '@/apis/1890.js'
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue'
import { computed, onMounted, reactive, toRefs } from 'vue'
import { cloneDeep } from 'lodash-es'
import { post, get } from 'server/axios'
import { evalPropChain } from '@/utils/utils.js'
const props = defineProps({
  // 自定义列配置
  /***
 columnName,
 fieldDescVo,
 isSelected,
 model,
 requestStr,
  searchStr,
  options:[],
  url: options数据的url
  labelValue： 自定义 options 中 value 的字段
  label：  自定义 options 中 label 的字段,
  respField: 'data.list'
   */
  columns: {
    type: Array,
    default: () => {
      return []
    }
  },
  menuName: {
    type: String,
    default: ''
  },
  componentConfig: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
const emits = defineEmits(['reset', 'search'])
// 定义收起时展示的个数
const DISPLAY_MAX_ON_FOLDED = 4
const AXIOS_METHOD = {
  get: get,
  post: post
}
const state = reactive({
  dataList: [],
  formdata: {},
  col: 3,
  isFolder: true,
  showMax: DISPLAY_MAX_ON_FOLDED
})

const searchDataList = computed(() => {
  return state.dataList?.filter(item => item.isSelected === 1) || []
})
const showSearchDataList = computed(() => {
  return searchDataList.value?.slice(0, state.showMax)
})
const colSpan = computed(() => {
  return 24 / state.col
})
const actionSpan = computed(() => {
  const r = showSearchDataList.value.length % 3
  return 24 - colSpan.value * r
})
const toggleMoreFilter = () => {
  state.isFolder = !state.isFolder
  if (!state.isFolder) {
    state.showMax = searchDataList.value.length
  } else {
    state.showMax = DISPLAY_MAX_ON_FOLDED
  }
}
const filterOption = (input, option) => {
  console.log(input, option)
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
/**
 * 根据接口返回的option数据设置Options数据并格式化处理
 * @param item
 * @param data
 */
const setOptionsData = (item, data) => {
  const optionLabelKey = item.label || 'key'
  const optionValueKey = item.labelValue || 'value'
  item.options = (data || [])
    .filter(_ => {
      return _[optionLabelKey] != null && _[optionLabelKey] !== ''
    })
    .map(_ => {
      return {
        label: _[optionValueKey],
        value: _[optionLabelKey]
      }
    })
}
const formatURL = url => {
  return url.startsWith('http') ? url : `${process.env.VUE_APP_CONFIG}/${url}`
}
/**
 * 根据url自定义获取options，主要用户手动自定义设置columns
 * @param item
 */
const getColoumnOptions = async item => {
  const method = (item.method || 'post').toLowerCase()
  const url = formatURL(item.url)
  const respField = item.respField || 'data'
  const resp = await AXIOS_METHOD[method](url, item.params || {})
  const data = evalPropChain(resp, respField)
  setOptionsData(item, data)
}
/**
 * 1、存在menuName时，使用后端的配置通用接口获取options
 * 2、不存在menuName时，存在配置自定义url时，需根据配置拉取options数据
 * @param item
 */
const getConfigColumn = async item => {
  if (!props.menuName) {
    item.url && getColoumnOptions(item)
    return false
  }

  const { success, data } = await config.list_column_post({
    menuName: item.menuName,
    columnName: item.searchStr
  })
  if (success) {
    setOptionsData(item, data)
  } else {
    console.log(data)
  }
}
/**
 * 根据自定义配置列初始化默认的formData数据
 * @param data
 */
const setInitFormData = data => {
  data?.map(item => {
    if (item.isSelected) {
      state.formdata[item.searchStr] = undefined
    }
    if (item.model === 5) {
      item.options = item.fieldDescVo
      const checkedValue = item.options.filter(item => item.checked)
      if (checkedValue.length) {
        if (item.isSelected) {
          state.formdata[item.searchStr] = checkedValue[0].value
        }
      }
    }
    if (props.componentConfig[item.searchStr]) {
      Object.assign(item, props.componentConfig[item.searchStr])
    }
  })
  state.defaultFormdata = cloneDeep(state.formdata)
  state.dataList = data
}
/**
 * 获取搜索条件的每一项
 */
const getMenuField = async () => {
  const { data } = await config.list_menu_field_post({
    menuName: props.menuName
  })
  setInitFormData(data)
}
const onSearch = () => {
  setTimeout(() => {
    emits('search', state.formdata)
  }, 200)
}
const onReset = () => {
  state.formdata = cloneDeep(state.defaultFormdata)
  setTimeout(() => {
    emits('reset', state.defaultFormdata)
  }, 200)
}
onMounted(() => {
  props.menuName && getMenuField()
  props.columns.length && setInitFormData(props.columns)
})
const { formdata } = toRefs(state)
</script>
<style lang="scss" scoped>
.ant-radio-wrapper {
  font-size: 12px;
}
</style>
